package com.phoenix.callAnalysis;

import com.phoenix.callAnalysis.models.LoadDataFlag;
import com.phoenix.callAnalysis.models.MyCall;
import com.phoenix.callAnalysis.task.GenericTask;
import com.phoenix.callAnalysis.task.TaskAdapter;
import com.phoenix.callAnalysis.task.TaskListener;
import com.phoenix.callAnalysis.task.TaskParams;
import com.phoenix.callAnalysis.task.TaskResult;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoadDataActivity extends BaseActivity {

	private static final String TAG = LoadDataActivity.class.getSimpleName();

	private Button startButton;
	private Button returnButton;
	private Button reloadButton;
	private ProgressBar mProgressBar;
	private TextView mTitleTextView;

	private int progressCount;
	// private int callsTotalCount = 0;
	private int needLoadCount = 0;
	private GenericTask mLoadDataTask;
	private TaskListener mLoadDataTaskListener = new TaskAdapter() {
		@Override
		public String getName() {
			return "mLoadDataTaskListener";
		}

		@Override
		public void onProgressUpdate(GenericTask task, Object param) {
			super.onProgressUpdate(task, param);
			TaskParams p = (TaskParams) param;
			progressCount = (Integer) p.get("count");
			mProgressBar.setProgress(progressCount);
			mTitleTextView.setText(CallAnalysisApplication.mUtils
					.getDynamicString(
							R.string.load_data_title_textview_loading,
							progressCount, needLoadCount));
		}

		@Override
		public void onPreExecute(GenericTask task) {
			super.onPreExecute(task);
			needLoadCount = CallAnalysisApplication.myCallLog.getCallsCount()
					- CallAnalysisApplication.myDB.getCallsCount();
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			super.onPostExecute(task, result);
			if (result == TaskResult.CANCELLED) {
				mTitleTextView
						.setText(R.string.load_data_title_textview_noNeed);
			} else if (result == TaskResult.OK) {
				mTitleTextView.setText(CallAnalysisApplication.mUtils
						.getDynamicString(
								R.string.load_data_title_textview_loadSuccess,
								mProgressBar.getMax()));
			}
		}

		@Override
		public void onCancelled(GenericTask task) {
			super.onCancelled(task);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate...");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.load_data);

		startButton = (Button) findViewById(R.id.load_data_title_start_button);
		returnButton = (Button) findViewById(R.id.load_data_title_return_button);
		reloadButton = (Button) findViewById(R.id.load_data_title_reload_button);
		mProgressBar = (ProgressBar) findViewById(R.id.load_data_title_progress_progressBar);
		mTitleTextView = (TextView) findViewById(R.id.load_data_title_textView);


		startButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startLoadData();
			}
		});
		returnButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(LoadDataActivity.this,
						CallAnalysisActivity.class));
				finish();
			}
		});
		reloadButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final AlertDialog.Builder builder = new AlertDialog.Builder(
						LoadDataActivity.this);
				builder.setTitle(R.string.reload_alertDialog_title);
				builder.setCancelable(true);
				builder.setPositiveButton(R.string.yes,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								CallAnalysisApplication.myDB.deleteCallsTable();
								startLoadData();
							}
						});
				builder.setNegativeButton(R.string.no,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						});
				builder.setMessage(R.string.reload_alertDialog_message);
				builder.create().show();
			}
		});

		if (!Eula.show(this)) {
			needLoadCount = CallAnalysisApplication.myCallLog.getCallsCount();
			updateTitleTextView(LoadDataFlag.FIRST_USE);
		} else {
			needLoadCount = CallAnalysisApplication.myCallLog.getCallsCount()
					- CallAnalysisApplication.myDB.getCallsCount();
			if (CallAnalysisApplication.needLoadData == LoadDataFlag.NO_DATA) {
				updateTitleTextView(LoadDataFlag.NO_DATA);
			}else
			if (CallAnalysisApplication.needLoadData == LoadDataFlag.NEED) {
				updateTitleTextView(LoadDataFlag.NEED);
			}else if (CallAnalysisApplication.needLoadData == LoadDataFlag.NO_NEED) {
				updateTitleTextView(LoadDataFlag.NO_NEED);
			}
		}
	}

	private boolean startLoadData() {
		if (mLoadDataTask != null
				&& mLoadDataTask.getStatus() == GenericTask.Status.RUNNING) {
			return true;
		} else {
			mLoadDataTask = new LoadDataTask();
			mLoadDataTask.setListener(mLoadDataTaskListener);
			mLoadDataTask.execute();
		}
		return true;
	}

	private void updateTitleTextView(LoadDataFlag flag) {
		if (flag == LoadDataFlag.FIRST_USE) {
			mTitleTextView.setText(CallAnalysisApplication.mUtils
					.getDynamicString(R.string.load_data_title_textview_first,
							needLoadCount));
		} else if (flag == LoadDataFlag.NO_DATA) {
			mTitleTextView.setText(CallAnalysisApplication.mUtils
					.getDynamicString(R.string.load_data_title_textview_noData,
							needLoadCount));
		} else if (flag == LoadDataFlag.NEED) {
			mTitleTextView.setText(CallAnalysisApplication.mUtils
					.getDynamicString(R.string.load_data_title_textview_need,
							needLoadCount));
		}else if (flag == LoadDataFlag.NO_NEED) {
			mTitleTextView.setText(R.string.load_data_title_textview_noNeed);
		}
	}

	private class LoadDataTask extends GenericTask {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			MyCall lastestCallInCallLog = CallAnalysisApplication.myCallLog
					.getLastestCall();
			MyCall lastestCallInMyDB = CallAnalysisApplication.myDB
					.getLastestCall();
			if (lastestCallInCallLog.equals(lastestCallInMyDB)) {
				return TaskResult.CANCELLED;
			}
			String[] requestedColumns = { CallLog.Calls.CACHED_NAME,
					CallLog.Calls.CACHED_NUMBER_LABEL,
					CallLog.Calls.CACHED_NUMBER_TYPE, CallLog.Calls.DATE,
					CallLog.Calls.DURATION, CallLog.Calls.NEW,
					CallLog.Calls.NUMBER, CallLog.Calls.TYPE };

			Cursor calls = null;
			try {
				calls = LoadDataActivity.this.getContentResolver().query(
						CallLog.Calls.CONTENT_URI, requestedColumns, null,
						null, CallLog.Calls.DEFAULT_SORT_ORDER);
				Log.d(TAG, "" + calls.getCount());
				Log.d(TAG, "" + CallAnalysisApplication.myDB.getCallsCount());
				mProgressBar.setMax(calls.getCount()
						- CallAnalysisApplication.myDB.getCallsCount());
				calls.moveToFirst();
				int count = 1;
				while (!calls.isAfterLast()) {
					MyCall call = new MyCall();
					call.setName(calls.getString(calls
							.getColumnIndex(CallLog.Calls.CACHED_NAME)));
					call.setNumberLabel(calls.getString(calls
							.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL)));
					call.setNumberType(calls.getInt(calls
							.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE)));
					call.setOccuredDate(calls.getLong(calls
							.getColumnIndex(CallLog.Calls.DATE)));
					call.setDuration(calls.getLong(calls
							.getColumnIndex(CallLog.Calls.DURATION)));
					call.setIsNew(calls.getInt(calls
							.getColumnIndex(CallLog.Calls.NEW)));
					call.setNumber(calls.getString(calls
							.getColumnIndex(CallLog.Calls.NUMBER)));
					call.setType(calls.getInt(calls
							.getColumnIndex(CallLog.Calls.TYPE)));
					if (call.equals(lastestCallInMyDB))
						break;
					CallAnalysisApplication.myDB.insertOneCall(call);
					TaskParams p = new TaskParams();
					p.put("count", count);
					publishProgress(p);
					count = count + 1;
					calls.moveToNext();
				}
			} catch (SQLiteException e) {
				Log.e(TAG, "getLastestCall()...");
				e.printStackTrace();
			} finally {
				if (calls != null && !calls.isClosed()) {
					calls.close();
				}
			}
			return TaskResult.OK;
		}
	}

}
